package com.ocom.webapi.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ocom.common.constant.WebApiServiceUrl;
import com.ocom.common.dto.Department;
import com.ocom.common.entity.master.EntityFileDownloadInfo;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.request.payconfig.AddSubsidyDataByPersonRequest;
import com.ocom.common.request.payconfig.AddSubsidyDataResquest;
import com.ocom.common.request.payconfig.SubsidyDataRequest;
import com.ocom.common.request.payconfig.SubsidyListRequest;
import com.ocom.common.resp.Result;
import com.ocom.common.response.web.SubsidyListResponse;
import com.ocom.common.utils.CommonUtil;
import com.ocom.common.utils.DateUtils;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.vo.GrantSubsidyVo;
import com.ocom.security.authentication.YoCiUser;
import com.ocom.security.utils.SecurityUtils;
import com.ocom.webapi.feign.AccessClientService;
import com.ocom.webapi.feign.HumanClientService;
import com.ocom.webapi.feign.MqSubsidyClientService;
import com.ocom.webapi.feign.PayConfigClientService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import static cn.hutool.poi.excel.cell.CellUtil.getCellValue;

@Slf4j
@RestController
@PreAuthorize("@pms.hasRole('ROLE_WEB')" )
public class SubsidyController {

    @Autowired
    PayConfigClientService payConfigClientService;

    @Autowired
    private MqSubsidyClientService maPayClientService;


    @Autowired
    private HumanClientService humanClientService;

    @Autowired
    AccessClientService accessClientService;


    /**
     *@Description:补贴计划（Subsidy/onShow）
     * @author lu 
     * @param subsidyListRequest
     * @return com.ocom.common.resp.Result
     * @date 2022/11/18 11:17       
     */
    @PostMapping(WebApiServiceUrl.URL_SubsidyOnShow)
    public Result subsidyOnShow(@RequestBody SubsidyListRequest subsidyListRequest){
        return payConfigClientService.subsidyList(subsidyListRequest);
    }

    /**
     *@Description:新增补贴计划（Subsidy/addSubsidy）
     * @author lu 
     * @param jsonObject 
     * @return com.ocom.common.resp.Result
     * @date 2022/11/18 11:31       
     */
    @PostMapping(WebApiServiceUrl.URL_SubsidyAddSubsidy)
    public Result subsidyAddSubsidy(@RequestBody JSONObject jsonObject){
        YoCiUser yoCiUser= SecurityUtils.getYoCiUser();
        jsonObject.put("userId",yoCiUser.getId());
        Result result =payConfigClientService.newSubsidyPlan(jsonObject);
        if (result.getCode()==200){
            //JSONObject subsidyId= JSON.parseObject(JSON.toJSONString(result.getData()),JSONObject.class);
            Integer planId =jsonObject.getInteger("oldSubsidyId");
            if (planId>0){
                return payConfigClientService.cloneSubsidyData(jsonObject);
            }

        }
        return result;
    }

    @PostMapping(WebApiServiceUrl.URL_SubsidyGrantSubsidy)
    public Result subsidyGrantSubsidy(@RequestBody JSONObject jsonObject){
        jsonObject.put("status",2);
        if(CommonUtil.isNull(jsonObject.getString("planDate"))){
            return ResultUtil.error(ResultEnum.Err_2033);
        }
        Result result =payConfigClientService.updateSubsidyPlan(jsonObject);
        if (jsonObject.getString("planDate").compareTo(DateUtils.getStrDate(new Date(),"yyyy-MM-dd"))<=0){
            GrantSubsidyVo grantSubsidyVo=new GrantSubsidyVo();
            grantSubsidyVo.setComId(jsonObject.getLong("comId"));
            grantSubsidyVo.setTimes(jsonObject.getInteger("times"));
            grantSubsidyVo.setMonth(jsonObject.getString("month"));
            return maPayClientService.grantSubsidy(grantSubsidyVo);
        }
        return result;
    }

    /**
     *@Description:停止发放补贴（Subsidy/stopSubsidy）
     * @author lu 
     * @param jsonObject
     * @return com.ocom.common.resp.Result
     * @date 2022/11/30 14:31       
     */
    @PostMapping(WebApiServiceUrl.URL_SubsidyStopSubsidy)
    public Result subsidyStopSubsidy(@RequestBody JSONObject jsonObject){
        Result result =payConfigClientService.updateSubsidyPlan(jsonObject);
        if (jsonObject.getInteger("status")==5){
            return payConfigClientService.grantSubsidy(jsonObject.getLong("comId"),jsonObject.getString("month"),jsonObject.getInteger("times"));
        }
        return result;
    }

    /**
     *@Description:补贴数据（Subsidy/subsidyList）
     * @author lu 
     * @param subsidyDataRequest
     * @return com.ocom.common.resp.Result
     * @date 2022/11/30 16:24       
     */
    @PostMapping(WebApiServiceUrl.URL_SubsidySubsidyList)
    public Result subsidySubsidyList(@RequestBody SubsidyDataRequest subsidyDataRequest){
        try {
            String deptIds="";
            if (subsidyDataRequest.getDeptId()==0){
                Department department=new Department();
                department.setComId(subsidyDataRequest.getComId());
                department.setDeptId(Long.valueOf(subsidyDataRequest.getDeptId()));
                department.setShowLevel(0);
                Result bootparentDeptId=humanClientService.getDeptIds(department);
                if (bootparentDeptId.getCode()==200){
                    JSONObject bootparentDeptIdObject= JSON.parseObject(JSON.toJSONString(bootparentDeptId.getData()));
                    deptIds=subsidyDataRequest.getDeptId()+","+bootparentDeptIdObject.getString("deptIds");
                }
            }
            subsidyDataRequest.setDeptIds(deptIds);
            return payConfigClientService.subsidyData(subsidyDataRequest);
        }catch (Exception e){
            log.info("补贴数据的异常信息:"+e);
            return ResultUtil.error(ResultEnum.Err_2009);
        }
    }

    /**
     *@Description:新增补贴人员（Subsidy/addPerson）
     * @author lu 
     * @param addSubsidyDataResquest
     * @return com.ocom.common.resp.Result
     * @date 2022/12/5 14:30       
     */
    @PostMapping(WebApiServiceUrl.URL_SubsidyAddPerson)
    public Result subsidyAddPerson(@RequestBody AddSubsidyDataResquest addSubsidyDataResquest){
        String deptIds="";
        YoCiUser yoCiUser= SecurityUtils.getYoCiUser();
        if (addSubsidyDataResquest.getDeptId()!=0){
            Department department=new Department();
            department.setComId(addSubsidyDataResquest.getComId());
            department.setDeptId(Long.valueOf(addSubsidyDataResquest.getDeptId()));
            department.setShowLevel(0);
            Result bootparentDeptId=humanClientService.getDeptIds(department);
            if (bootparentDeptId.getCode()==200){
                JSONObject bootparentDeptIdObject= JSON.parseObject(JSON.toJSONString(bootparentDeptId.getData()));
                deptIds=addSubsidyDataResquest.getDeptId()+","+bootparentDeptIdObject.getString("deptIds");
            }
        }
        addSubsidyDataResquest.setDeptIds(deptIds);
        addSubsidyDataResquest.setUserId(yoCiUser.getId());
        return payConfigClientService.addSubsidyData(addSubsidyDataResquest);
    }

    /**
     *@Description:批量设置补贴金额
     * @author lu 
     * @param addSubsidyDataResquest
     * @return com.ocom.common.resp.Result
     * @date 2022/12/5 14:32       
     */
    @PostMapping(WebApiServiceUrl.URL_SubsidyModifyAmount)
    public Result subsidyModifyAmount(@RequestBody AddSubsidyDataResquest addSubsidyDataResquest){
        YoCiUser yoCiUser= SecurityUtils.getYoCiUser();
        addSubsidyDataResquest.setUserId(yoCiUser.getId());
        return payConfigClientService.updateSubsidyMoney(addSubsidyDataResquest);
    }

    /**
     *@Description:批量删除补贴人员（Subsidy/deletePerson）
     * @author lu 
     * @param addSubsidyDataResquest
     * @return com.ocom.common.resp.Result
     * @date 2022/12/5 16:02       
     */
    @PostMapping(WebApiServiceUrl.URL_SubsidyDeletePerson)
    public Result subsidyDeletePerson(@RequestBody AddSubsidyDataResquest addSubsidyDataResquest){
        return payConfigClientService.removeSubsidyData(addSubsidyDataResquest);
    }

    /**
     *@Description:导出补贴计划（Subsidy/exportPlan）
     * @author lu 
     * @param subsidyListRequest
     * @return com.ocom.common.resp.Result
     * @date 2022/12/6 16:16       
     */
    @PostMapping(WebApiServiceUrl.URL_SubsidyExportPlan)
    public Result subsidyExportPlan(@RequestBody SubsidyListRequest subsidyListRequest){
        EntityFileDownloadInfo entityFileDownloadInfo=new EntityFileDownloadInfo();
        YoCiUser yoCiUser= SecurityUtils.getYoCiUser();
        entityFileDownloadInfo.setPId(yoCiUser.getId());
        entityFileDownloadInfo.setName("导出补贴计划");
        entityFileDownloadInfo.setStatus(0l);
        Result result=accessClientService.SendExcelApply(entityFileDownloadInfo);
        if(result.getCode()!=200){
            return ResultUtil.error(ResultEnum.Err_4013);
        }
        subsidyListRequest.setId((Integer)result.getData());
        return maPayClientService.subsidyList(subsidyListRequest);
    }

    /**
     *@Description:导出补贴数据（Subsidy/exportData）
     * @author lu 
     * @param subsidyDataRequest
     * @return com.ocom.common.resp.Result
     * @date 2022/12/6 16:17       
     */
    @PostMapping(WebApiServiceUrl.URL_SubsidyExportData)
    public Result subsidyExportData(@RequestBody SubsidyDataRequest subsidyDataRequest){
        EntityFileDownloadInfo entityFileDownloadInfo=new EntityFileDownloadInfo();
        YoCiUser yoCiUser= SecurityUtils.getYoCiUser();
        entityFileDownloadInfo.setPId(yoCiUser.getId());
        entityFileDownloadInfo.setName("导出补贴数据");
        entityFileDownloadInfo.setStatus(0l);
        Result result=accessClientService.SendExcelApply(entityFileDownloadInfo);
        if(result.getCode()!=200){
            return ResultUtil.error(ResultEnum.Err_4013);
        }
        subsidyDataRequest.setId((Integer)result.getData());
        return maPayClientService.subsidyData(subsidyDataRequest);
    }

    /**
     *@Description:导入补贴数据（Subsidy/importData）
     * @author lu 
     * @param comId
     * @param month
     * @param times
     * @param file
     * @return com.ocom.common.resp.Result
     * @date 2023/1/3 14:21       
     */
    @PostMapping(WebApiServiceUrl.URL_SubsidyimportData)
    public Result subsidyImportData(Long comId,String month,Integer times,@RequestPart("file") MultipartFile file){

        Workbook workbook = null ;
        String fileName = file.getOriginalFilename();
        if(fileName.endsWith("xls")){
            //2003
            try {
                workbook = new HSSFWorkbook(file.getInputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else if(fileName.endsWith("xlsx")){
            //2007
            try {
                workbook = new XSSFWorkbook(file.getInputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            try {
                throw new Exception("文件不是Excel文件");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        Sheet sheet = workbook.getSheetAt(0);
        int rows = sheet.getLastRowNum();// 指的行数，一共有多少行+
        if(rows==0){
            try {
                throw new Exception("请填写数据");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        SubsidyListRequest subsidyListRequest=new SubsidyListRequest();
        subsidyListRequest.setComId(comId);
        subsidyListRequest.setBeginMonth(month);
        subsidyListRequest.setEndMonth(month);
        subsidyListRequest.setStrStatus("1");
        subsidyListRequest.setPage(-1);
        subsidyListRequest.setSize(-1);
        Result result=payConfigClientService.subsidyList(subsidyListRequest);
        if (result.getCode()!=200){
            return result;
        }
       JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(result.getData()),JSONObject.class);
        List<SubsidyListResponse> listResponses= JSONArray.parseArray(JSON.toJSONString(jsonObject.get("list")),SubsidyListResponse.class);
        if (listResponses.size()<=0){
            return ResultUtil.error(ResultEnum.Err_4070);
        }
        int subsidyId=0;
        int wallet=0;
        for (SubsidyListResponse listRespons : listResponses) {
            if (listRespons.getMonth().equals(month) && listRespons.getTimes().compareTo(times)==0){
                subsidyId=listRespons.getSubsidyId();
                wallet  = listRespons.getWallet();
            }
        }
        AddSubsidyDataByPersonRequest addSubsidyDataByPersonRequest=new AddSubsidyDataByPersonRequest();
        addSubsidyDataByPersonRequest.setComId(comId);
        addSubsidyDataByPersonRequest.setPlanId(subsidyId);
        addSubsidyDataByPersonRequest.setMonth(month);
        addSubsidyDataByPersonRequest.setTimes(times);
        addSubsidyDataByPersonRequest.setWallet(wallet);
        addSubsidyDataByPersonRequest.setPId(0L);

        int errCount = 0;
        BREAKOFF:
        for (int i = 1; i < rows+1; i++) {
            if(i>5005){
                break BREAKOFF;
            }
            // 读取左端单元格
            Row row = sheet.getRow(i);
            if (row != null) {
                String pCode = JSON.toJSONString(getCellValue(row.getCell(0))).replace("\"", "").replace("\\t", "");
                if(CommonUtil.isNull(pCode)){
                    errCount++;
                    if(errCount>10){
                        break BREAKOFF;
                    }
                    continue  ;
                }else{
                    errCount = 0;
                }
                String pName = JSON.toJSONString(getCellValue(row.getCell(1))).replace("\"", "").replace("\\t", "");
                String planMoney = JSON.toJSONString(getCellValue(row.getCell(2))).replace("\"", "").replace("\\t", "");
                BigDecimal moneyBig  = new BigDecimal(planMoney);
                BigDecimal dev  = new BigDecimal(100);
                Integer intplanMoney= moneyBig.multiply(dev).intValue();
                addSubsidyDataByPersonRequest.setPCode(pCode);
                addSubsidyDataByPersonRequest.setPlanMoney(intplanMoney);
                maPayClientService.subsidyDataAddPerson(addSubsidyDataByPersonRequest);
            }
        }
        return ResultUtil.success();
    }
}
